/*
 * XmlSampleTable.cpp
 *
 *  Created on: 2015年6月12日
 *      Author: chuanjiang.zh@qq.com
 */

#include "XmlSampleTable.h"
#include "tinyxml.h"
#include "TStringUtil.h"

static std::string toXml(TiXmlNode* node)
{
    TiXmlPrinter printer;
    node->Accept(&printer);
    return printer.CStr();
}

static size_t replace(std::string& str, const std::string& pattern, const std::string& value)
{
    size_t count = 0;
    size_t start = 0;
    size_t pos = str.find(pattern, start);
    while (pos != std::string::npos)
    {
        str.replace(pos, pattern.size(), value);
        count ++;

        start = pos;
        pos = str.find(pattern, start);
    }
    return count;
}

XmlSampleTable::XmlSampleTable()
{
}

XmlSampleTable::~XmlSampleTable()
{
}

bool XmlSampleTable::load(const std::string& filename)
{
    TiXmlDocument doc;
    if (!doc.LoadFile(filename.c_str()))
    {
        return false;
    }

    XmlSample sample;

    TiXmlElement* root = doc.RootElement();
    TiXmlNode* node = root->FirstChild();
    while (node)
    {
        TiXmlNode::NodeType type = (TiXmlNode::NodeType)node->Type();
        if (type == TiXmlNode::TINYXML_COMMENT)
        {
            TiXmlComment* comment = node->ToComment();
            sample.name = comment->Value();
            comn::StringUtil::trim(sample.name);
        }
        else if (type == TiXmlNode::TINYXML_ELEMENT)
        {
            sample.xml = toXml(node);
            replace(sample.xml, "&quot;", "\"");
            push_back(sample);
        }

        node = node->NextSibling();
    }

    return true;
}
